package com.faner4cloud.yun.common.util.progress.timer;

import com.faner4cloud.yun.common.util.progress.Progress;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @author Jail.Hu
 * @date 2019年8月16日 下午12:12:25
 * @copyright (c) 2019, Lianjia Group All Rights Reserved.
 */
class DefaultTimer implements ProcessTimer {

	private final TimerConfig config;
	private Thread timing;

	public DefaultTimer(TimerConfig config) {
		super();
		this.config = config;
	}

	@Override
	public void start(Progress progress) {
		if (this.timing != null || progress == null) {
			return;
		}
		this.timing = new Timer("progress-timer-" + progress.getIdentity(), this.config, progress);
		this.timing.start();
	}

	@Override
	public void interrupt() {
		if (this.timing != null) {
			this.timing.interrupt();
		}
	}

	class Timer extends Thread {

		private final TimeUnit unit;
		private final long interval;
		private final Consumer<Progress> timingConsumer;
		private Progress progress;

		public Timer(String name, TimerConfig config, Progress progress) {
			super(name);
			this.unit = config.getUnit();
			this.interval = config.getInterval();
			this.timingConsumer = config.getTimingConsumer();
			this.progress = progress;
		}

		@Override
		public void run() {
			while (!isInterrupted()) {
				this.timingConsumer.accept(this.progress);
				try {
					this.unit.sleep(this.interval);
				} catch (InterruptedException e) {
					break;
				}
			}
		}
	}

}
